// pages/myPintuaDetail/myPintuaDetail.js 拼团详情
let url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var const_js = require("../../utils/const.js");
var user_js = require("../../utils/user.js");
var sys_js = require("../../utils/system.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    groupId: '', //团购id
    item: null,
    sysInfo: null,
    contentStatus: -1,
    tPersonList: [],
    tHistoryPersonList: [],
    timerObj: { //拼团计时器对象
      timer: null,
      isEnd: false,
      endTime: '',
      item: null
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
    //2.请求数据
    this.requestToGetGroupInfo(this.data.groupId);
  },

  //初始化数据
  initData: function(options) {
    var tmpGroupId = options.groupId ? options.groupId : '';

    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo,
      groupId: tmpGroupId
    });
  },

  //获取团购详情信息
  requestToGetGroupInfo: function(groupId) {
    var data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      shopId: this.data.userInfo.ztd.id,
      groupId: groupId
    }
    api.wxRequest(url_js.groupInfoUrl, data).then(res => {
      this.handelGroupInfoData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的团购详情信息
  handelGroupInfoData: function(res) {
    var tmpItem = res.result;
    if (!tmpItem) {
      common_js.showToast("拼团不存在");
      return;
    }

    //处理参团人数的list 
    var tmpTuanPersonList = [];
    var tmpHistoryList = [];
    //添加团长
    var tzItem = {};
    tzItem.id = tmpItem.initiatorUserId;
    tzItem.joinTime = tmpItem.createTime;
    tzItem.nickName = tmpItem.nickName;
    tzItem.profilePhoto = tmpItem.initiatorHeadImg;
    tzItem.isLeader = true;
    tmpTuanPersonList.push(tzItem);
    tmpHistoryList.push(tzItem);

    //添加数据
    var followList = tmpItem.followerList;
    var followCount = followList.length;
    for (var i = 0; i < tmpItem.size - 1; i++) {
      if (i < followCount) {
        tmpTuanPersonList.push(followList[i]);
        tmpHistoryList.push(followList[i]);
      } else {
        tmpTuanPersonList.push({});
      }
    }

    //如果是拼团中，开启计时器
    var tmpTimerObj = this.data.timerObj;
    if (tmpItem.groupStatus == 0 && tmpItem.expire > 0) {
      tmpTimerObj.endTime = new Date().getTime() + tmpItem.expire * 1000;
    }
    //set dasta
    this.setData({
      item: tmpItem,
      tPersonList: tmpTuanPersonList,
      tHistoryPersonList: tmpHistoryList,
      timerObj: tmpTimerObj,
      contentStatus: 1
    });

    //开启计时器
    if (tmpItem.groupStatus == 0 && tmpItem.expire > 0) {
      this.countDownTimer();
    }

    //1.开启转发
    wx.showShareMenu({});
  },

  //显示商品团购活动状态,1进行中，0没有团购活动
  requestToGroupStatusInfo: function(groupId, productId, shareShopId) {
    var data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      shopId: this.data.userInfo.ztd.id,
      groupId: groupId,
      productId: productId,
      shareShopId: shareShopId
    }
    api.wxRequest(url_js.productGroupStatusUrl, data).then(res => {
      this.handelGroupStatusData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的商品团购活动状态
  handelGroupStatusData: function(res) {
    var tmpInfo = res.result;
    if (tmpInfo.state == 1) {
      //1当前商品有团购
      wx.navigateTo({
        url: '../goodsDetails/goodsDetails?productId=' + this.data.item.productId + '&groupId=' + this.data.item.groupId
      });
    } else if (tmpInfo.state == 2) {
      //当前商品没有团购，但是其它商品有团购
      common_js.showModal("该商品已恢复原价，看看其他拼团商品？", null, true, "算了", "去看看", () => {
        //拼团列表
        wx.navigateTo({
          url: '../groupBuyingList/groupBuyingList'
        })
      });
    } else if (tmpInfo.state == 3) {
      //3，没有拼团活动
      common_js.showModal("拼团活动已结束，看看其他推荐商品？", null, true, "算了", "去看看", () => {
        //分类
        wx.switchTab({
          url: '/pages/category/category'
        });
      });
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    //开启计时器
    if (this.data.timerObj.groupStatus == 0 && this.data.timerObj.expire > 0) {
      if (this.data.timerObj.timer) {
        clearTimeout(this.data.timerObj.timer);
      }
    }
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myPintuaDetailYqpy);

    return this.shareAppMessage();
  },

  //获取分享的AppMessage
  shareAppMessage: function() {
    var tmpPath = '/pages/goodsDetails/goodsDetails' + '?productId=' + this.data.item.productId + '&shareShopId=' + this.data.userInfo.ztd.id + '&userId=' + this.data.userInfo.userInfo.id;
    return {
      title: this.data.item.title ? this.data.item.title : '大牛惠生活',
      path: tmpPath,
      imageUrl: this.data.item.mainImage
    }
  },

  //订单详情
  onOrderDetail: function(e) {
    wx.navigateTo({
      url: '../myOrderDetail/myOrderDetail?orderId=' + this.data.item.orderId
    });
  },

  //我要开团
  onWykt: function(e) {
    this.requestToGroupStatusInfo(this.data.item.groupId, this.data.item.productId, this.data.userInfo.ztd.id);
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.myPintuaDetailWykt);
  },

  // 抢购计时器**********
  countDownTimer() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    var tmpTimerObj = this.data.timerObj;
    let endTime = tmpTimerObj.endTime;;

    // 对结束时间进行处理渲染到页面
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let dayHour = (day > 0) ? day * 24 : 0;
      let hou = dayHour + parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: common_js.timeFormat(day),
        hou: common_js.timeFormat(hou),
        min: common_js.timeFormat(min),
        sec: common_js.timeFormat(sec)
      }
    } else { //活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
      tmpTimerObj.isEnd = true;
    }
    tmpTimerObj.item = obj;
    //1s调用一次
    var that = this;
    var timerItem = setTimeout(function() {
      that.countDownTimer();
    }, 1000);
    //定时清除
    clearTimeout(this.data.timerObj.timer);
    if (tmpTimerObj.isEnd) {
      clearTimeout(timerItem);
      return;
    } else {
      tmpTimerObj.timer = timerItem;
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      timerObj: tmpTimerObj
    })
  }
  // 抢购计时器**********
})